import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/model/device_obj/data_type_model.dart';
import 'package:yt_devops/model/device_obj/output_data_model.dart';
import 'package:yt_devops/model/device_obj/spec/double_spec.dart';
import 'package:yt_devops/model/device_obj/spec/struct_spec.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/add_mains_electricity_price/views/effective_data_widget.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/brn_row1_delegate.dart';
import 'package:yt_devops/utils/number_input_limit_formatter.dart';
import 'package:yt_devops/utils/toast_utils.dart';

// {
//                     "accessType": "push",
//                     "dataType": {
//                         "specs": {
//                             "item ": {
//                                 "specs": [
//                                     {
//                                         "dataType": {
//                                             "specs": {
//                                                 "length": "11"
//                                             },
//                                             "type": "timeRange"
//                                         },
//                                         "id": "pcsRunningTimeFrame1",
//                                         "name": "运行时段1"
//                                     },
//                                     {
//                                         "dataType": {
//                                             "specs": {
//                                                 "0": "充电",
//                                                 "1": "放电"
//                                             },
//                                             "type": "enum"
//                                         },
//                                         "id": "chargingAndDischargingMode",
//                                         "name": "充放电模式"
//                                     },
//                                     {
//                                         "dataType": {
//                                             "specs": {
//                                                 "max": "10000000000",
//                                                 "min": "0",
//                                                 "unit": "kW",
//                                                 "unitName": "千瓦"
//                                             },
//                                             "type": "double"
//                                         },
//                                         "id": "executionPower",
//                                         "name": "执行功率"
//                                     }
//                                 ],
//                                 "type": " struct"
//                             },
//                             "size": "10"
//                         },
//                         "type": "array"
//                     },
//                     "groupName": "",
//                     "id": "PeriodOfTime",
//                     "name": "时段"
//                 }
//             ]
//         },

class ArrayWidget extends StatefulWidget {
  /// 物模型
  final DataTypeModel arrayModel;

  /// 最多可添加的条数
  final int maxNum;

  /// name
  final String? name;

  /// 数据变化回调
  Function(List)? onChange;

  ///数据源回调
  List? dataSource;

  late DataTypeEnum dataTypeEnum;

  ArrayWidget(
      {super.key,
      required this.arrayModel,
      int? maxLength,
      this.name,
      this.dataSource,
      this.onChange})
      : maxNum = maxLength ?? 100,
        dataTypeEnum = arrayModel
            .type; //dataType 如果是 [struct] ,则是多组合控件数组， 如果是array 则是单组合控件数组， 其他的则是单控件

  @override
  State<ArrayWidget> createState() => _ArrayWidgetState();
}

class _ArrayWidgetState extends State<ArrayWidget> {
  List<OutputDataModel> outputDataModelArray = [];
  OutputDataModel? outputDataModel;

  /// 数据
  List _data = [];

  @override
  void initState() {
    if (widget.dataTypeEnum == DataTypeEnum.struct) {
      for (var item in ((widget.arrayModel.specs as StructSpec).specs
          as List<OutputDataModel>)) {
        outputDataModelArray.add(item);
      }
    } else {}
    _data = widget.dataSource ?? [];
    super.initState();
  }

  @override
  void didUpdateWidget(covariant ArrayWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    // var itemModel = arrayModel;
    return ListView.separated(
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        itemBuilder: (context, index) {
          Widget widgets;
          if (index == _data.length) {
            widgets = GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: toAdd,
                child: Container(
                  height: 49,
                  color: Colour.white,
                  child: Row(
                    children: [
                      Container(
                        padding: EdgeInsets.only(left: 16, right: 16),
                        child: Image.asset(
                          'assets/images/site_elec_price_add.png',
                          height: 18,
                          width: 18,
                        ),
                      ),
                      Text(
                        '${ResKey.add.tr}${widget.name}',
                        style: ytTextStyle(
                            fontWeight: FontWeight.normal,
                            color: Colour.primaryColor,
                            fontSize: 14),
                      ),
                    ],
                  ),
                ));
          } else {
            switch (widget.dataTypeEnum) {
              case DataTypeEnum.struct:
                widgets = structCard(index);

                break;
              default:
                widgets = SizedBox();
            }
          }
          return widgets;
        },
        separatorBuilder: (context, index) => const Divider(
              height: 1,
            ),
        itemCount: _data.length + 1);
  }

  Map<String, dynamic> getNewDataModel(
      Map<String, dynamic> dataMap, OutputDataModel model) {
    var value;
    if (model.dataType.type == DataTypeEnum.string) {
      value = '';
    } else if (model.dataType.type == DataTypeEnum.long ||
        model.dataType.type == DataTypeEnum.double) {
      value = '';
    } else if (model.dataType.type == DataTypeEnum.timeRange) {
      value = '-';
    } else {
      value = '';
    }

    return dataMap..putIfAbsent(model.id, () => value);
  }

  toAdd() {
    if (_data.length >= widget.maxNum) {
      return TotastUtils.tip(context, title: '超出长度限度，最多可添加${widget.maxNum}条数据');
    }
    Map<String, dynamic> dataMap = {};
    if (widget.dataTypeEnum == DataTypeEnum.struct ||
        widget.dataTypeEnum == DataTypeEnum.array) {
      for (var item in outputDataModelArray) {
        dataMap = getNewDataModel(dataMap, item);
      }
    } else {
      dataMap = getNewDataModel(dataMap, outputDataModel!);
    }

    _data.add(dataMap);
    widget.onChange?.call(_data);
    setState(() {});
  }

  ListView structCard(int dataIndex) {
    return ListView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          var item = outputDataModelArray[index];
          DataTypeEnum type = item.dataType.type;
          if (type == DataTypeEnum.timeRange) {
            return timeRangeWidget(item, dataIndex);
          } else if (type == DataTypeEnum.enumType) {
            return enumPickerWidget(item, dataIndex);
          } else if (type == DataTypeEnum.double ||
              type == DataTypeEnum.long ||
              type == DataTypeEnum.string) {
            return inputWiget(item, dataIndex);
          } else {
            return SizedBox();
          }
        },
        itemCount: outputDataModelArray.length);
  }

  ///
  ///[dataIndex] 在数据中的索引值
  /// [model]格式如下
  /// ```dart
  /// {
  ///  "dataType": {
  ///  "specs": {
  ///    "0": "尖",
  ///    "1": "峰",
  ///    "2": "平",
  ///    "3": "谷"
  ///    },
  ///     "type": "enum"
  ///   },
  ///   "id": "ElectrovalenceType",
  ///    "name": "电价类型"
  /// }
  /// ```dart
  ///
  Widget enumPickerWidget(OutputDataModel model, int dataIndex) {
    Map spec = model.dataType.specs as Map;
    return Container(
      height: 48,
      color: Colour.white,
      child: Row(
        children: [
          Gaps.hGap16,
          Text(
            model.name,
            style: ytTextStyle(
                fontWeight: FontWeight.normal,
                color: Colour.lightTextColor,
                fontSize: 14),
          ),
          Spacer(),
          GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                List<String> list =
                    spec.values.map((e) => e.toString()).toList();
                showBottomPop(context, list, model.name, confirmClick: (idx) {
                  _data[dataIndex][model.id] = spec.keys.toList()[idx];
                  widget.onChange?.call(_data);
                  setState(() {});
                });
                // typeClickCallBack();
              },
              child: Stack(
                alignment: Alignment.centerRight,
                children: [
                  Container(
                    decoration: const BoxDecoration(
                        color: Colour.backgroundColor,
                        borderRadius: BorderRadius.all(Radius.circular(4))),
                    height: 32,
                    width: 106.w,
                    alignment: Alignment.center,
                    child: Text(
                      spec[_data[dataIndex][model.id].toString()] ?? '',
                      style: ytTextStyle(
                          fontWeight: FontWeight.normal, fontSize: 14),
                    ),
                  ),
                  Positioned(
                    child: Icon(Icons.expand_more),
                    right: 8.w,
                  )
                ],
              )),
          Container(
            width: 169.w,
          )
        ],
      ),
    );
  }

  ///
  /// 输入样式
  /// [dataIndex] 在数据中的索引值
  /// [model]格式如下
  /// {
  /// "dataType": {
  /// "specs": {
  ///       "max": "10000000000",
  ///       "min": "0",
  ///       "unit": "kW",
  ///       "unitName": "千瓦"
  ///   },
  ///   "type": "double"
  ///  },
  ///    "id": "executionPower",
  ///    "name": "执行功率"
  ///}
  ///
  ///
  inputWiget(OutputDataModel model, int dataIndex) {
    DataTypeEnum type = model.dataType.type;
    String unit = '';
    TextInputType keyboardType;
    List<TextInputFormatter> inputFormatter = [];
    if (type == DataTypeEnum.double || type == DataTypeEnum.long) {
      var spec = model.dataType.specs as DoubleSpec;
      unit = spec.unit ?? '';
      keyboardType = const TextInputType.numberWithOptions(decimal: true);
      inputFormatter = [
        NumberInputLimitFormatter(max: spec.max ?? 99999999, min: spec.min ?? 0)
      ];
    } else {
      keyboardType = TextInputType.text;
    }
    return Container(
      height: 48,
      color: Colour.white,
      child: Row(
        children: [
          Gaps.hGap16,
          SizedBox(
            width: 81.w,
            child: Text(
              model.name,
              style: ytTextStyle(
                  fontWeight: FontWeight.normal,
                  color: Colour.lightTextColor,
                  fontSize: 14),
            ),
          ),
          Spacer(),
          Container(
              decoration: const BoxDecoration(
                  color: Colour.backgroundColor,
                  borderRadius: BorderRadius.all(Radius.circular(4))),
              height: 32,
              width: 106.w,
              alignment: Alignment.center,
              child: TextField(
                textAlignVertical: TextAlignVertical.center,
                textAlign: TextAlign.center,
                style:
                    const TextStyle(fontSize: 14, color: Colour.mainTextColor),
                controller: TextEditingController(
                    text: _data[dataIndex][model.id]?.toString() ?? ''),
                keyboardType: keyboardType,
                inputFormatters: inputFormatter,
                decoration: const InputDecoration(
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.only(bottom: 13),
                  enabled: true,
                  hintStyle: TextStyle(
                      fontSize: 14.0,
                      color: Colour.lightTextColor,
                      fontWeight: FontWeight.normal),
                ),
                onChanged: (String str) {
                  _data[dataIndex][model.id] = str;
                  widget.onChange?.call(_data);
                },
              )),
          Container(
            padding: EdgeInsets.only(left: 4.w),
            width: 169.w,
            child: Text(
              unit,
              style: ytTextStyle(fontWeight: FontWeight.normal, fontSize: 14),
            ),
          )
        ],
      ),
    );
  }

  ///
  ///
  ///
  ///[dataIndex] 在数据中的索引值
  /// [model]格式如下
  /// ```dart
  /// {
  ///"dataType": {
  ///    "specs": {
  ///        "length": "11"
  ///    },
  ///    "type": "timeRange"
  ///},
  ///"id": "pcsRunningTimeFrame1",
  ///"name": "运行时段1"
  ///},
  /// ```dart
  ///
  timeRangeWidget(OutputDataModel model, int dataIndex) {
    String? timeFrame = _data[dataIndex][model.id];
    var range = timeFrame?.split('-') ?? ['', ''];
    return EffectiveDataWidget(
      context,
      '${'siteMonitor.TimePeriod'.tr}${dataIndex + 1}',
      range[0],
      range[1],
      (startDateTime, endDateTime) {
        var time = '$startDateTime-$endDateTime';
        var isOverLap = isTimeOverLap(
            _data.map((e) => e[model.id] as String).toList()
              ..removeAt(dataIndex),
            time);
        if (isOverLap == true) {
          TotastUtils.tip(context, title: ResKey.timePeriodsOverlap.tr);
        } else {
          _data[dataIndex][model.id] = time;
          setState(() {});
        }
      },
      () {
        _data.removeAt(dataIndex);
        widget.onChange?.call(_data);
        setState(() {});
      },
      isShowHour: true,
      isDelete: true,
    );
  }

  ///弹出底部弹窗
  showBottomPop(BuildContext context, List<String> list, String title,
      {void Function(dynamic)? confirmClick}) {
    BrnMultiDataPicker(
      context: context,
      title: title,
      confirmClick: (indexList) {
        if (indexList.isNotEmpty) {
          Log.d('indexList==' + indexList[0].toString());
          confirmClick?.call(indexList[0]);
        }
      },
      delegate: Brn1RowDelegate(list),
    ).show();
  }

  ///
  /// 计算所选时间和已选的时间段是否有重合
  /// 这里的时间段格式是 "09:33-14:50"
  ///
  bool? isTimeOverLap(List<String> timeFrameList, String time) {
    if (time.isEmpty || !time.contains('-')) {
      return null;
    }
    var timeList = time.split('-');
    String start1 = timeList[0];
    String end1 = timeList[1];
    for (int i = 0; i < timeFrameList.length; i++) {
      if (timeFrameList[i].isEmpty || !timeFrameList[i].contains('-')) {
        continue;
      }
      var times = timeFrameList[i].split('-');
      String start2 = times[0];
      String end2 = times[1];

      if ((timeFrameToMinut(start1) ?? 0) < (timeFrameToMinut(end2) ?? 0) &&
          (timeFrameToMinut(end1) ?? 0) > (timeFrameToMinut(start2) ?? 0)) {
        return true;
      }
    }

    return false;
  }

  int? timeFrameToMinut(String time) {
    if (time.isEmpty || !time.contains(':')) {
      return null;
    }
    var timeList = time.split(':');
    return int.parse(timeList[0]) * 60 + int.parse(timeList[1]);
  }
}
